package com.example.examsystem.repository;

import com.example.examsystem.model.Exam;
import com.example.examsystem.model.ExamStatus;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 考试数据访问层
 */
@Repository
public interface ExamRepository extends JpaRepository<Exam, Long> {
    
    /**
     * 根据学科ID统计考试数量
     */
    long countBySubjectId(Long subjectId);
    
    /**
     * 根据标题查找考试
     */
    List<Exam> findByTitleContaining(String title);
    
    /**
     * 根据状态查找考试
     */
    List<Exam> findByStatus(ExamStatus status);
    
    /**
     * 根据学科ID查找考试
     */
    List<Exam> findBySubjectId(Long subjectId);
    
    /**
     * 分页查询考试（支持ExamStatus枚举和学科ID）
     */
    @Query("""
       SELECT e FROM Exam e
       WHERE
           (:query IS NULL OR :query = '' 
               OR LOWER(e.title) LIKE LOWER(CONCAT('%', :query, '%')) 
               OR LOWER(e.description) LIKE LOWER(CONCAT('%', :query, '%'))) 
           AND (:status IS NULL OR e.status = :status) 
           AND (:subjectId IS NULL OR e.subjectId = :subjectId)
       """)
    Page<Exam> findByQuery(@Param("query") String query,
                          @Param("status") ExamStatus status,
                          @Param("subjectId") Long subjectId,
                          Pageable pageable);
}